/*
* Copyright 2017 Yonyou Auto Information Technology（Shanghai） Co., Ltd. All Rights Reserved.
*
* This software is published under the terms of the YONYOU Software
* License version 1.0, a copy of which has been included with this
* distribution in the LICENSE.txt file.
*
* @Project Name : marketing-service-questionnaire
*
* @File name : QuestionnaireService.java
*
* @Author : Administrator
*
* @Date : 2017年3月7日
*
----------------------------------------------------------------------------------
*     Date       Who       Version     Comments
* 1. 2017年3月7日    Administrator    1.0
*
*
*
*
----------------------------------------------------------------------------------
*/

package com.yonyou.gmmc.service.questionnaire.service;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.marketing.common.constants.ExceptionMessage;
import org.marketing.common.dto.customerInfo.CarInfoDto;
import org.marketing.common.dto.customerInfo.MemberDto;
import org.marketing.common.dto.information.QuestionnaireaDto;
import org.marketing.common.exception.ServiceBizException;
import org.marketing.common.util.CheckUtil;
import org.marketing.common.util.DateUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.yonyou.gmmc.service.questionnaire.dao.TmQuestionMapper;
import com.yonyou.gmmc.service.questionnaire.dao.TtOwnerQuestionnaireMapper;
import com.yonyou.gmmc.service.questionnaire.dao.TtQneResultMapper;
import com.yonyou.gmmc.service.questionnaire.dao.TtQuestionnaireMapper;
import com.yonyou.gmmc.service.questionnaire.dao.TtShareLogMapper;
import com.yonyou.gmmc.service.questionnaire.dto.NaireCommit;
import com.yonyou.gmmc.service.questionnaire.dto.QustionShare;
import com.yonyou.gmmc.service.questionnaire.model.TtOwnerQuestionnaire;
import com.yonyou.gmmc.service.questionnaire.model.TtOwnerQuestionnaireExample;
import com.yonyou.gmmc.service.questionnaire.model.TtOwnerQuestionnaireExample.Criteria;
import com.yonyou.gmmc.service.questionnaire.model.TtQneResult;
import com.yonyou.gmmc.service.questionnaire.model.TtQuestionnaire;
import com.yonyou.gmmc.service.questionnaire.model.TtShareLog;

import tk.mybatis.mapper.entity.Example;

/**
 *
 * @date 2017年3月7日
 */

@Transactional
@Service
public class QuestionnaireService {
	private Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private TtOwnerQuestionnaireMapper ttOwnerQuestionnaireMapper;
	@Autowired
	private TmQuestionMapper tmQuestionMapper;

	@Autowired
	private TtQneResultMapper ttQneResultMapper;

	@Autowired
	private TtQuestionnaireMapper ttQuestionnaireMapper;

	@Autowired
	private TtShareLogMapper ttShareLogMapper;

	@Autowired
	private QuestionnaireServiceInterface questionnaireServiceInterface;

	public List<Map<String, Object>> getQnaireType(Integer type, String userId, String openId) {
		List<Map<String, Object>> list = new ArrayList<>();
		Map<String, Object> map = new HashMap<>();
		map.put("queryType", type);
		if(CheckUtil.NullOrEmpty(openId)){
			map.put("userId", userId);
			map.put("userType", 2);
		}else{
			List<MemberDto> dtoList = ttOwnerQuestionnaireMapper.queryPotential(openId);
			if(!CheckUtil.NullOrEmpty(dtoList)){
				map.put("userId", userId);
				map.put("userType", 2);
			}else{
				map.put("userId", dtoList.get(0).getPotentialUserId());
				map.put("userType", 1);
			}
		}

		list = ttOwnerQuestionnaireMapper.getQnaireType(map);
		return list;
	}

	public Map<String, Object> getExplainVies(Integer id) {
		return ttOwnerQuestionnaireMapper.getExplainVies(id);
	}
	
	public Map<String, Object> questionNaireDetail(Integer id, String userId, String openId) {
		List<Map<String, Object>> resultList = new ArrayList<>();
		Map<String, Object> result = new HashMap<>();
		List<Map<String, Object>> list = new ArrayList<>();
		Map<String,Object> asMap = new HashMap<>();
		List<Map<String, Object>> questionList = tmQuestionMapper.questionNaireDetail(id);
		if (!CheckUtil.NullOrEmpty(userId)) {
			Map<String, Object> map = new HashMap<>();
			map.put("qneId", id);
			if(CheckUtil.NullOrEmpty(openId)){
				map.put("userId", userId);
				map.put("userType", 2);
			}else{
				List<MemberDto> dtoList = ttOwnerQuestionnaireMapper.queryPotential(openId);
				if(!CheckUtil.NullOrEmpty(dtoList)){
					map.put("userId", userId);
					map.put("userType", 2);
				}else{
					map.put("userId", dtoList.get(0).getPotentialUserId());
					map.put("userType", 1);
				}
			}
			list = ttQneResultMapper.getResultList(map);
		}
		if (!CheckUtil.NullOrEmpty(questionList)) {
			for (int i = 0; i < questionList.size(); i++) {
				String QTN_ID = questionList.get(i).get("QTN_ID")==null?"0":questionList.get(i).get("QTN_ID").toString();
				String type = questionList.get(i).get("QT_TYPE")==null?"":questionList.get(i).get("QT_TYPE").toString();
				String title = questionList.get(i).get("QT_TITLE")==null?"":questionList.get(i).get("QT_TITLE").toString();
				Map<String, Object> qItem = new HashMap<>();
				Map<String, Object> itemMap = new HashMap<>();
				List<Map<String, Object>> currentList = new ArrayList<>();
				itemMap.put("name", QTN_ID.toString());
				itemMap.put("isRequired", true);
				itemMap.put("type", type);
				itemMap.put("title", title);
				
				for(int k=0;k<list.size();k++){
					String i_QTN_ID = list.get(k).get("QTN_ID").toString();
					if(i_QTN_ID.equals(QTN_ID)){
						asMap.put(QTN_ID.toString(), list.get(k).get("USER_ANSWER"));
					}
				}
				List<Map<String, Object>> choiceList = new ArrayList<>();
				List<Map<String, Object>> answerList = tmQuestionMapper.getAnswer(Integer.valueOf(QTN_ID));
	            for (int j = 0; j < answerList.size(); j++) {
	                String text = (String) answerList.get(j).get("ANSWER");
	                Integer value = Integer.valueOf(answerList.get(j).get("ANSWER_ID").toString());
	                Map<String, Object> cMap = new HashMap<String, Object>();
	                cMap.put("text", text);
	                cMap.put("value", value);
	                choiceList.add(cMap);
	            }
				itemMap.put("choices", choiceList);
				currentList.add(itemMap);
				qItem.put("name", "page" + i);
				qItem.put("questions", currentList);
				resultList.add(qItem);
			}
		}
		result.put("pages", resultList);
		result.put("asMap", asMap);
		return result;
	}

	public void commitNaire(NaireCommit commit, String userId, String openId) {
		List<MemberDto> dtoList = new ArrayList<>();
		if(CheckUtil.NullOrEmpty(openId)){
			dtoList = ttOwnerQuestionnaireMapper.queryMember(Integer.valueOf(userId));
		}else{
			dtoList = ttOwnerQuestionnaireMapper.queryPotential(openId);
		}
		String dealerCode = dtoList.get(0).getDealerCode();
		String vin = dtoList.get(0).getVin();
		String completionDate = null;
		if (vin != null && !vin.equals("")) {
			completionDate = ttOwnerQuestionnaireMapper.queryVin(vin);
		}

		TtOwnerQuestionnaire toqp = new TtOwnerQuestionnaire();
		/* 校验twoId是否合法，否则抛出异常，并提示客户端 */
		toqp.setId(commit.getTwoId());
		List<TtOwnerQuestionnaire> toqpList = ttOwnerQuestionnaireMapper.select(toqp);
		if (toqpList == null
				|| toqpList.size() == 0) {/* 校验用户问卷关系是否真实存在，否则抛出异常，并提示客户端 */
			throw new ServiceBizException(ExceptionMessage.APP_QUESTIONNAIRE_COMMIT_QUESTION_OWNER_ID_ERROR);
		}
		String[] qids = commit.getQuestionId().split(",");
		String[] ans = commit.getAnswer().split(";");
		for (int i = 0; i < ans.length; i++) {
			// 判断id是否和问题id相等
			if (qids[i].equals(ans[i].substring(ans[i].indexOf("/@") + 2))) {
				TtQneResult tp = new TtQneResult();
				//tp.setOwnerId(Integer.valueOf(userId));
				tp.setQneId(Integer.parseInt(commit.getQneId()));
				tp.setQtnId(Integer.parseInt(ans[i].substring(ans[i].indexOf("/@") + 2)));
				tp.setSubmitTime(new Date());
				tp.setUserQneRefId(commit.getTwoId());// 设置用户问卷关系编号
				tp.setUserAnswer(ans[i].substring(0, ans[i].indexOf("/@")));
				ttQneResultMapper.insertSelective(tp);
			} else {
				throw new ServiceBizException(ExceptionMessage.APP_QUESTIONNAIRE_COMMIT_QUESTION_ANSWER_MISMATCH);
			}

		}
		// 如何去判断是不是一类的问卷
		TtOwnerQuestionnaire record = new TtOwnerQuestionnaire();
		record.setId(commit.getTwoId());
		TtOwnerQuestionnaire toqMap = ttOwnerQuestionnaireMapper.selectOne(record);
		if (!CheckUtil.NullOrEmpty(toqMap) && !CheckUtil.NullOrEmpty(toqMap.getBizCode2())
				&& toqMap.getBizCode2().equals("1")) {// 如果取出来的BIZ_CODE2=1那么就说明已经被答过了
			throw new ServiceBizException(ExceptionMessage.APP_QUESTIONNAIRE_COMMITED);
		} else {
			// 更新对应的所有的同样的问卷都为已答题
			TtOwnerQuestionnaireExample ex = new TtOwnerQuestionnaireExample();
			Criteria cr = ex.createCriteria();
			cr.andIdEqualTo(commit.getTwoId());
			TtOwnerQuestionnaire tt = new TtOwnerQuestionnaire();
			tt.setBizCode1(completionDate);
			tt.setBizCode2(commit.getSfdt());
			tt.setBizCode3(dealerCode);
			tt.setBizCode4(vin);
			tt.setUserSubmitDate(new Date());
			int a = ttOwnerQuestionnaireMapper.updateByExampleSelective(tt, ex);
			if (a != 1) {// twoId具有唯一性，如果受影响的条数不等于1则抛出异常，回滚事务
				throw new ServiceBizException(ExceptionMessage.APP_QUESTIONNAIRE_COMMIT_QUESTION_OWNER_ID_ERROR);
			}
		}

		try {
			// 判断是否为会员
//			if (dtoList.get(0).getUserId() == null) {
//				logger.info("不是会员，不加分");
//			} else {
//				// 是会员,提交问卷完成，发放积分
//				logger.info("提交问卷完成发积分_Start");
//				TtQuestionnaire tq = new TtQuestionnaire();
//				tq.setQneId(Integer.valueOf(commit.getQneId()));
//				TtQuestionnaire t = ttQuestionnaireMapper.selectOne(tq);
//				EventCommitQuesionnaireDTO etDto = new EventCommitQuesionnaireDTO();
//				etDto.setUserId(dtoList.get(0).getUserId());
//				etDto.setPhone(dtoList.get(0).getPhone());
//				etDto.setQneId(t.getQneId());
//				etDto.setSharingPoints(t.getSharingPoints());
//				logger.info("问卷积分SHARINGPOINTS为：" + etDto.getSharingPoints());
//				BizEvent event = new BizEvent();
//				event.setEventKey("WJTJ" + "-" + etDto.getUserId() + "-" + etDto.getPhone() + "-" + commit.getQneId());
//				event.setEventBizType(EventBizType.QUESTIONNAIRE);
//				event.setEventBizStep(EventBizStep.QUESTIONNAIRE_COMMIT);
//				event.setEventData(MapConverUtil.PO2Map(etDto));
//				eventService.sendEvent2MQ(event);
//				logger.info("提交问卷完成发积分_End");
//			}
//			
//			 //发放卡券
//            logger.info("自动发放卡券");
//            SendTicket ticketDto = new SendTicket();
//            ticketDto.setBizCode(1009);
//            ticketDto.setTriggerCode(10091001);
//            ticketDto.setUserId(userId);
//            logger.info("该用户的销售店为："+dealerCodes);
//            if(dealerCodes!=null){
//                ticketDto.setDealerCode(dealerCodes);
//            }else{
//                ticketDto.setDealerCode("");
//            }
//            ticketDto.setBatchId("");
//            ticketDto.setBizId(commit.getTwoId().toString());
//            BizEvent et = new BizEvent();
//            et.setEventBizType(EventBizType.SEND_TICKET);
//            et.setEventBizStep(EventBizStep.SEND_TICKTE_TO_USER);
//            et.setEventKey("TICKET:"+ticketDto.getUserId()+":"+new Date().getTime());
//            et.setEventData(MapConverUtil.PO2Map(ticketDto));
//            String s = eventService.sendEvent2MQ(et);
//            logger.info("发放卡券MQ返回结果>>>>>>>>>>>>>>>>>>>>" + s);
		} catch (Exception e) {
			logger.info("提交问卷完成发积分_End" + e);
		}
	}

	public int share(QustionShare qustionShare) {
		TtShareLog tp = new TtShareLog();
		tp.setBizCaseName(qustionShare.getBizName());
		tp.setContent(qustionShare.getContent());
		tp.setShareDate(new Date());
		// modify by wdl
		// shareType为空Integer.parseInt报错
		// 如果为空，设置默认为1，为微信分享
		// end
		if (!CheckUtil.NullOrEmpty(qustionShare.getShareType())) {
			tp.setShareType(Short.parseShort(qustionShare.getShareType()));
		} else {
			tp.setShareType((short) 1);
		}
		tp.setShareTo(qustionShare.getShareTo());
		// modify by wdl 2015-12-17
		// 没有登录进行分享，则userId为空;
		if (!CheckUtil.NullOrEmpty(qustionShare.getUserId())) {
			tp.setUserId(Integer.parseInt(qustionShare.getUserId()));
		} else {
			tp.setUserId(0);
		}
		tp.setSsiId(qustionShare.getSsid());
		tp.setBizId(qustionShare.getBizId());
		return ttShareLogMapper.insertBase(tp);
	}

	/**
	 * 问卷
	 * 
	 * @author Administrator
	 * @date 2017年3月23日
	 * @return
	 */
	public List<QuestionnaireaDto> queryQuestionnaire(String openId) {
		List<QuestionnaireaDto> dtoList = tmQuestionMapper.queryQuestionnaire(openId);
		return dtoList;
	}

	/**
	 * 推送调查问卷
	 * 
	 * @author Administrator
	 * @date 2017年6月2日
	 * @return
	 * @throws Exception
	 */
	public Map<String, Object> sendQuestionnaire() throws Exception {
		Map<String, Object> result = new HashMap<String, Object>();
		List<CarInfoDto> list = new ArrayList<CarInfoDto>();
		String content = "";
        String qne = "";
        String type = "";
        List<String> paramList = new ArrayList<>();
        Map<String,Object> paramMap = new HashMap<>();
		try {
			// 1.交车日期+3~交车日期+3+90
			list = ttOwnerQuestionnaireMapper.querySales();
			type = "1";
			qne = ttOwnerQuestionnaireMapper.selectQne(type);
			if(qne==null||qne==""){
			    logger.info("暂无问卷！");
			}else{
	            if (list.size() == 0) {
	                logger.info("没有符合条件(交车日期+3~交车日期+3+90)的人，不推送消息");
	            } else if (list.size() == 1) {
	                logger.info("有一条符合条件(交车日期+3~交车日期+3+90)的，调用接口推送");
	                String openId = list.get(0).getOpenId();
	                logger.info("用户的OPEN_ID为>>>>>>>>" + openId);
                    logger.info("绑定问卷和发送人——START");
                    paramList.add(openId);
                    paramMap.put("qnt", qne);
                    paramMap.put("list", paramList);
                    logger.info("paramMap为》》》》》"+paramMap.toString());
	                bindQuestionUser(paramMap);
	                logger.info("绑定问卷和发送人——END");
	                content = "您的满意是我们最大的动力。诚邀您参与本次购车调查，帮助我们持续改善为您提供更优质的服务。<a href=\"www.baidu.com\">点击参与</a>";
	                logger.info("推送的消息内容为>>>>>>>>>" + content);
	                Map<String, Object> salesMap = questionnaireServiceInterface.sendMessage(openId, content);
	                logger.info("返回结果为>>>>>>>>" + salesMap);
	            } else {
	                for(int i=0;i<list.size();i++){
                        paramList.add(i, list.get(i).getOpenId());
	                }
                    logger.info("绑定问卷和发送人——START");
                    paramMap.put("qnt", qne);
                    paramMap.put("list", paramList);
                    logger.info("paramMap为》》》》》"+paramMap.toString());
                    bindQuestionUser(paramMap);
                    logger.info("绑定问卷和发送人——END");
	                logger.info("调用群发接口推送消息");
	                String openId_List = "";
	                for (int i = 0; i < list.size() - 1; i++) {
	                    openId_List = openId_List + "\"" + list.get(i).getOpenId() + "\",";
	                }
	                openId_List = openId_List + "\"" + list.get(list.size()).getOpenId() + "\"";
	                logger.info("群发的openId列表为>>>>>>" + openId_List);
	                content = "您的满意是我们最大的动力。诚邀您参与本次购车调查，帮助我们持续改善为您提供更优质的服务。<a href=\"www.baidu.com\">点击参与</a>";
	                logger.info("推送的消息内容为>>>>>>>>>" + content);
	                Map<String, Object> salesMap = questionnaireServiceInterface.mass(openId_List, content);
	                logger.info("返回结果为>>>>>>>>" + salesMap);
	            }
			}
			// 2.交车日期+7~交车日期+7+90
			list = ttOwnerQuestionnaireMapper.queryAfterSale();
            type = "2";
            qne = ttOwnerQuestionnaireMapper.selectQne(type);
            if(qne==null||qne==""){
                logger.info("暂无问卷！");
            }else{
                if (list.size() == 0) {
                    logger.info("没有符合条件(交车日期+7~交车日期+7+90)的人，不推送消息");
                } else if (list.size() == 1) {
                    logger.info("有一条符合条件(交车日期+7~交车日期+7+90)的，调用接口推送");
                    String openId = list.get(0).getOpenId();
                    logger.info("用户的OPEN_ID为>>>>>>>>" + openId);
                    logger.info("绑定问卷和发送人——START");
                    paramList.add(openId);
                    paramMap.put("qnt", qne);
                    paramMap.put("list", paramList);
                    logger.info("paramMap为》》》》》"+paramMap.toString());
                    bindQuestionUser(paramMap);
                    logger.info("绑定问卷和发送人——END");
                    content = "您的满意是我们最大的动力。诚邀您参与本次购车调查，帮助我们持续改善为您提供更优质的服务。<a href=\"www.baidu.com\">点击参与</a>";
                    logger.info("推送的消息内容为>>>>>>>>>" + content);
                    Map<String, Object> afterSaleMap = questionnaireServiceInterface.sendMessage(openId, content);
                    logger.info("返回结果为>>>>>>>>" + afterSaleMap);
                } else {
                    for(int i=0;i<list.size();i++){
                        paramList.add(i, list.get(i).getOpenId());
                    }
                    logger.info("绑定问卷和发送人——START");
                    paramMap.put("qnt", qne);
                    paramMap.put("list", paramList);
                    logger.info("paramMap为》》》》》"+paramMap.toString());
                    bindQuestionUser(paramMap);
                    logger.info("绑定问卷和发送人——END");
                    logger.info("调用群发接口推送消息");
                    logger.info("调用群发接口推送消息");
                    String openId_List = "";
                    for (int i = 0; i < list.size() - 1; i++) {
                        openId_List = openId_List + "\"" + list.get(i).getOpenId() + "\",";
                    }
                    openId_List = openId_List + "\"" + list.get(list.size()).getOpenId() + "\"";
                    //扫描 1163
                    //logger.info("群发的openId列表为>>>>>>" + openId_List);
                    content = "您的满意是我们最大的动力。诚邀您参与本次购车调查，帮助我们持续改善为您提供更优质的服务。";
                    logger.info("推送的消息内容为>>>>>>>>>" + content);
                    Map<String, Object> afterSaleMap = questionnaireServiceInterface.mass(openId_List, content);
                    logger.info("返回结果为>>>>>>>>" + afterSaleMap);
                }
            }
			// 3.养修完成+3
			list = ttOwnerQuestionnaireMapper.queryMaintain();
            type = "3";
            qne = ttOwnerQuestionnaireMapper.selectQne(type);
            if(qne==null||qne==""){
                logger.info("暂无问卷！");
            }else{
                if (list.size() == 0) {
                    logger.info("没有符合条件(养修完成+3)的人，不推送消息");
                } else {
                    logger.info("符合条件(养修完成+3)的，调用接口推送");
                    for (int i = 0; i < list.size(); i++) {
                        String openId = list.get(i).getOpenId();
                        paramList.add(i, list.get(i).getOpenId());
                        content = "亲爱的客户" + list.get(i).getUserName() + "，您的爱车" + list.get(i).getRegistNo() + "于"
                                + list.get(i).getReseApplEndTime() + "已经维修完成，请您协助完成本次售后满意度调查";
                        logger.info("推送给客户的消息为>>>>>>" + content);
                        Map<String, Object> maintainMap = questionnaireServiceInterface.sendMessage(openId, content);
                        logger.info("返回结果为>>>>>>>>" + maintainMap);
                    }
                    logger.info("绑定问卷和发送人——START");
                    paramMap.put("qnt", qne);
                    paramMap.put("list", paramList);
                    bindQuestionUser(paramMap);
                    logger.info("绑定问卷和发送人——END");
                }
            }
		} catch (Exception e) {
			logger.error(e.getMessage(), e);
			throw new ServiceBizException(e.getMessage(), e);
		}
		return result;
	}

	/**
	 * 推送调查问卷
	 * 
	 * @author Administrator
	 * @date 2017年6月2日
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public void bindQuestionUser(Map<String, Object> map) {
		Integer qnt = Integer.valueOf(map.get("qnt").toString());
		List<String> list = (List<String>) map.get("list");
		if (!CheckUtil.NullOrEmpty(list) && list.size() > 0) {
			for (String m : list) {
				// 绑定用户和问卷
				TtOwnerQuestionnaire tq = new TtOwnerQuestionnaire();
				tq.setQneId(qnt);
				tq.setUserId(Integer.parseInt(m));
				tq.setCreateDate(new Date());
				ttOwnerQuestionnaireMapper.insertSelective(tq);
			}
		}
	}
	/**
	 * 绑定新注册用户调查问卷
	 * 
	 * @author Administrator
	 * @date 2017年6月2日
	 * @return
	 * @throws Exception
	 */
	public void bindNewUser() throws Exception {
		Integer i = 0;
		Example ex = new Example(TtQuestionnaire.class);
		tk.mybatis.mapper.entity.Example.Criteria criteria =ex.createCriteria();
		criteria.andEqualTo("qneType", "5");
		criteria.andCondition("to_char(qne_end_date,'yyyy-MM-dd')>=", DateUtil.formateDate(new Date(), "yyyy-MM-dd"));
		List<TtQuestionnaire> list = ttQuestionnaireMapper.selectByExample(ex);
		if (!CheckUtil.NullOrEmpty(list) && list.size() > 0) {
			for (TtQuestionnaire q : list) {
				String isCarOwner = q.getUserType();
				Integer qneId = q.getQneId();
				logger.info("======>绑定已存在问卷:"+qneId);
				String begin = q.getGcBeginDate()==null?"":DateUtil.formateDate(q.getGcBeginDate(), "yyyy-MM-dd");
				String end = q.getGcEndDate()==null?"":DateUtil.formateDate(q.getGcEndDate(), "yyyy-MM-dd");
				String rzbegin = q.getRzBeginDate()==null?"":DateUtil.formateDate(q.getRzBeginDate(), "yyyy-MM-dd");
				String rzend = q.getRzEndDate()==null?"":DateUtil.formateDate(q.getRzEndDate(), "yyyy-MM-dd");
				String citys = "";
				//类型 0车型等级 1调查城市
				List<String> cList = ttQuestionnaireMapper.queryQueModel(q.getQneId(),1);
				if (!CheckUtil.NullOrEmpty(cList)&&!cList.isEmpty()) {
					for (String str : cList) {
						if(!"ALL".equals(str)){
							citys += "'"+str+"',";
			            }
	                }
					if(!CheckUtil.NullOrEmpty(citys)){
						citys=citys.substring(0, citys.length()-1);
					}
		        }
				if(CheckUtil.NullOrEmpty(isCarOwner)||isCarOwner.equals("1,2,3")){
					List<Integer> poList = ttQuestionnaireMapper.queryPotential(citys,qneId);
					i = i + bindQueUser(poList,qneId,"1");
					List<Integer> usList = ttQuestionnaireMapper.queryUser(citys,qneId);
					i = i + bindQueUser(usList,qneId,"2");
					Map<String, String> map = carUser(q);
					List<Integer> caList = ttQuestionnaireMapper.queryCarUser(map.get("modelCode"),citys,map.get("dealerCode")
							,map.get("lastCode"),map.get("chepai"),begin,end,rzbegin,rzend,qneId);
					i = i + bindQueUser(caList,qneId,"2");
		        }else if(isCarOwner.equals("1")){
		        	List<Integer> poList = ttQuestionnaireMapper.queryPotential(citys,qneId);
					i = i + bindQueUser(poList,qneId,"1");
		        }else if(isCarOwner.equals("2")){
		        	List<Integer> usList = ttQuestionnaireMapper.queryUser(citys,qneId);
					i = i + bindQueUser(usList,qneId,"2");
		        }else if(isCarOwner.equals("3")){
					Map<String, String> map = carUser(q);
					List<Integer> caList = ttQuestionnaireMapper.queryCarUser(map.get("modelCode"),citys,map.get("dealerCode")
							,map.get("lastCode"),map.get("chepai"),begin,end,rzbegin,rzend,qneId);
					i = i + bindQueUser(caList,qneId,"2");
		        }else if(isCarOwner.equals("1,3")){
		        	List<Integer> poList = ttQuestionnaireMapper.queryPotential(citys,qneId);
					i = i + bindQueUser(poList,qneId,"1");
					Map<String, String> map = carUser(q);
					List<Integer> caList = ttQuestionnaireMapper.queryCarUser(map.get("modelCode"),citys,map.get("dealerCode")
							,map.get("lastCode"),map.get("chepai"),begin,end,rzbegin,rzend,qneId);
					i = i + bindQueUser(caList,qneId,"2");
		        }else if(isCarOwner.equals("2,3")){
					List<Integer> usList = ttQuestionnaireMapper.queryUser(citys,qneId);
					i = i + bindQueUser(usList,qneId,"2");
					Map<String, String> map = carUser(q);
					List<Integer> caList = ttQuestionnaireMapper.queryCarUser(map.get("modelCode"),citys,map.get("dealerCode")
							,map.get("lastCode"),map.get("chepai"),begin,end,rzbegin,rzend,qneId);
					i = i + bindQueUser(caList,qneId,"2");
		        }else if(isCarOwner.equals("1,2")){
		        	List<Integer> poList = ttQuestionnaireMapper.queryPotential(citys,qneId);
					i = i + bindQueUser(poList,qneId,"1");
					List<Integer> usList = ttQuestionnaireMapper.queryUser(citys,qneId);
					i = i + bindQueUser(usList,qneId,"2");
		        }
			}
		}
		logger.info("======>绑定新注册用户和问卷数量为:"+i);
	}
	/**
	 * 绑定新注册用户调查问卷
	 * 
	 * @author Administrator
	 * @date 2017年6月2日
	 * @return
	 */
	public Integer bindQueUser(List<Integer> list,Integer qneId,String userType){
		Integer i = 0;
		if (!CheckUtil.NullOrEmpty(list) && !list.isEmpty()) {
			for (Integer q : list) {
				// 绑定用户和问卷
				TtOwnerQuestionnaire toq = new TtOwnerQuestionnaire();
				toq.setQneId(qneId);
				toq.setUserId(q);
				toq.setBizCode5(userType);
				toq.setCreateDate(new Date());
				ttOwnerQuestionnaireMapper.insertSelective(toq);
				i++;
				logger.warn("======>绑定用户和问卷...userId:"+q+"   qneId:"+qneId);
			}
		}
		return i;
	}
	/**
	 * 车主筛选条件
	 * 
	 * @author Administrator
	 * @date 2017年6月2日
	 * @return
	 */
	public Map<String, String> carUser(TtQuestionnaire q){
		Map<String, String> result = new HashMap<>();
		if (!CheckUtil.NullOrEmpty(q.getQnePlate())) {
			String chepai = "";
			for (String str : q.getQnePlate().split(",")) {
				chepai += "'"+str+"',";
            }
			chepai=chepai.substring(0, chepai.length()-1);
			result.put("chepai", chepai);
		}
		List<String> mList = ttQuestionnaireMapper.queryQueModel(q.getQneId(),0);
		if (!CheckUtil.NullOrEmpty(mList)&&!mList.isEmpty()) {
			String modelCode = "";
			for (String str : mList) {
				if(!"ALL".equals(str)){
					modelCode += "'"+str+"',";
	            }
            }
			if(!CheckUtil.NullOrEmpty(modelCode)){
				modelCode=modelCode.substring(0, modelCode.length()-1);
			}
			result.put("modelCode", modelCode);
        }
		List<String> dList = ttQuestionnaireMapper.queryQueScope(q.getQneId(),"dealerCode");
		if (!CheckUtil.NullOrEmpty(dList)&&!dList.isEmpty()) {
			String dealerCode = "";
			for (String str : dList) {
				if(!"ALL".equals(str)){
					dealerCode += "'"+str+"',";
	            }
            }
			if(!CheckUtil.NullOrEmpty(dealerCode)){
				dealerCode=dealerCode.substring(0, dealerCode.length()-1);
			}
			result.put("dealerCode", dealerCode);
        }
		List<String> lList = ttQuestionnaireMapper.queryQueScope(q.getQneId(),"lastDealerCode");
		if (!CheckUtil.NullOrEmpty(lList)&&!lList.isEmpty()) {
			String lastCode = "";
			for (String str : lList) {
				if(!"ALL".equals(str)){
					lastCode += "'"+str+"',";
	            }
            }
			if(!CheckUtil.NullOrEmpty(lastCode)){
				lastCode=lastCode.substring(0, lastCode.length()-1);
			}
			result.put("lastCode", lastCode);
        }
		return result;
	}
	
	public void updatePotentialToUser() {
		Integer i = 0;
		Example ex = new Example(TtOwnerQuestionnaire.class);
		tk.mybatis.mapper.entity.Example.Criteria criteria =ex.createCriteria();
		criteria.andEqualTo("bizCode5", "1");
		List<TtOwnerQuestionnaire> list = ttOwnerQuestionnaireMapper.selectByExample(ex);
		if (!CheckUtil.NullOrEmpty(list)) {
			for (TtOwnerQuestionnaire q : list) {
				List<MemberDto> member = ttOwnerQuestionnaireMapper.queryPotentialById(q.getUserId());
				if(!CheckUtil.NullOrEmpty(member) && !CheckUtil.NullOrEmpty(member.get(0).getUserId())){
					TtOwnerQuestionnaire oq = new TtOwnerQuestionnaire();
					oq.setId(q.getId());
					oq.setUserId(member.get(0).getUserId());
					oq.setBizCode5("2");
					ttOwnerQuestionnaireMapper.updateByPrimaryKeySelective(oq);
					i++;
				}
				
			}
		}
		logger.info("======>自动更新新注册用户的问卷绑定的ID数量为:"+i);
	}
}
